import Vue from "vue";
import VueRouter from "vue-router";
import Login from "@/views/login/Login.vue";
import Test from "@/views/login/test.vue";
import Layout from "@/views/layout/Layout.vue";

Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject);
  }
  return originalPush.call(this, location).catch((err) => {
    if (err.name !== "NavigationDuplicated") {
      // 如果不是 NavigationDuplicated 错误，重新抛出
      throw err;
    }
    // 否则，可以选择忽略或记录
    // console.warn("导航到相同路由被忽略:", err);
    return this.currentRoute;
  });
};
const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/test",
    name: "Test",
    component: Test,
  },
  {
    path: "/",
    component: Layout,
    redirect: "/home",
    children: [
      {
        path: "home",
        name: "Home",
        component: () => import("@/views/home/Home.vue"),
        meta: { requiresAuth: true, roles: ["*"] },
      },
    ],
  },
];
const router = new VueRouter({
  routes,
});

// router.beforeEach(async (to, from, next) => {
//   const token = localStorage.getItem("token");

//   if (to.path === "/login") {
//     next();
//     return;
//   }

//   if (!token) {
//     next("/login");
//     return;
//   }
//   // 以下是示例代码，需要根据需要自行修改
//   if (to.meta.requiresAuth) {
//     const rolelist = store.getters["user/getuser"];
//     const roleid = rolelist.roleid;

//     if (to.meta.roles.includes("*")) {
//       next();
//     } else if (to.meta.roles.includes("admin") && roleid == 1) {
//       next();
//     } else {
//       next("/");
//     }
//   }

//   try {
//     // 调用后端 API 验证 token 有效性
//     const response = await validateToken(token);
//     if (response.code != 200) {
//       localStorage.removeItem("token");
//       next("/login");
//     }
//   } catch (error) {
//     console.error("Token 验证失败:", error);
//     localStorage.removeItem("token");
//     next("/login");
//   }
// });

export default router;
